import {
	ref,
	watch
} from 'vue';

import {
	cosSecret
} from '@/common/apis/other'

import COS from 'cos-wx-sdk-v5'

export const useCos = async function(item) {
	console.log('上传：', item)
	const cosdata = await cosSecret()
	const strBefore = item.match('[^/]+(?!.*/)')[0]
	const str = `${cosdata.tempUploadPath}${strBefore}`
	const cosapi = new COS({
		getAuthorization(options, callback) {
			callback({
				TmpSecretId: cosdata.credentials.tmpSecretId,
				TmpSecretKey: cosdata.credentials.tmpSecretKey,
				SecurityToken: cosdata.credentials.sessionToken,
				ExpiredTime: cosdata.expiredTime
			})
		}
	})
	
	const postObjectAsync = () => {
		return new Promise((resolve, reject) => {
			cosapi.postObject({
				Bucket: cosdata.bucket,
				Region: cosdata.region,
				Key: str,
				FilePath: item
			}, (err, data) => {
				console.log('上传了：', data, err)
				if (data) {
					resolve(data)
				} else {
					uni.showToast({ icon: 'none', title: '保存图片失败' })
					reject(err)
				}
			})
		})
	}
	let resdata = await postObjectAsync()
	
	return { cosdata, strBefore, str, cosapi, resdata }
}